<?php

function RunMagicQuotes(&$str)
{
    if (!get_magic_quotes_gpc()) {
        if (is_array($str))
            foreach ($str as $key => $val)
                $str[$key] = RunMagicQuotes($val);
        else
            $str = addslashes($str);
    }
    return $str;
}

function gdversion()
{
    //没启用php.ini函数的情况下如果有GD默认视作2.0以上版本
    if (!function_exists('phpinfo')) {
        if (function_exists('imagecreate'))
            return '2.0';
        else
            return 0;
    }
    else {
        ob_start();
        phpinfo(8);
        $module_info = ob_get_contents();
        ob_end_clean();
        if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i", $module_info, $matches)) {
            $gdversion_h = $matches[1];
        } else {
            $gdversion_h = 0;
        }
        return $gdversion_h;
    }
}

function TestWrite($d)
{
    $tfile = '_dedet.txt';
    $d = preg_replace('/\/$/', '', $d);
    $fp = @fopen($d . '/' . $tfile, 'w');
    if (!$fp)
        return false;
    else {
        fclose($fp);
        $rs = @unlink($d . '/' . $tfile);
        if ($rs)
            return true;
        else
            return false;
    }
}

function ReWriteConfigAuto()
{
    global $dsql;
    $configfile = DEDEROOT . '/data/config.cache.inc.php';
    if (!is_writeable($configfile)) {
        echo "配置文件'{$configfile}'不支持写入，无法修改系统配置参数！";
        //ClearAllLink();
        exit();
    }
    $fp = fopen($configfile, 'w');
    flock($fp, 3);
    fwrite($fp, "<" . "?php\r\n");
    $dsql->SetQuery("Select `varname`,`type`,`value`,`groupid` From `#@__sysconfig` order by aid asc ");
    $dsql->Execute();
    while ($row = $dsql->GetArray()) {
        if ($row['type'] == 'number')
            fwrite($fp, "\${$row['varname']} = " . $row['value'] . ";\r\n");
        else
            fwrite($fp, "\${$row['varname']} = '" . str_replace("'", '', $row['value']) . "';\r\n");
    }
    fwrite($fp, "?" . ">");
    fclose($fp);
}

/**
 * 获得数据库列表
 *
 * @access  public
 * @param   string      $db_host        主机
 * @param   string      $db_port        端口号
 * @param   string      $db_user        用户名
 * @param   string      $db_pass        密码
 * @return  mixed       成功返回数据库列表组成的数组，失败返回false
 */
function get_db_list($db_host, $db_user, $db_pass)
{
    $databases = array();
    $filter_dbs = array('information_schema', 'mysql');
    $conn = @mysql_connect($db_host, $db_user, $db_pass);

    if ($conn === false) {
        return false;
    }

    $result = mysql_query('SHOW DATABASES', $conn);
    if ($result !== false) {
        while (($row = mysql_fetch_assoc($result)) !== false) {
            if (in_array($row['Database'], $filter_dbs)) {
                continue;
            }
            $databases[] = $row['Database'];
        }
    } else {
        $err->add($_LANG['query_failed']);
        return false;
    }
    @mysql_close($conn);

    return $databases;
}

/**
 * 创建配置文件
 *
 * @access  public
 * @param   string      $db_host        主机
 * @param   string      $db_port        端口号
 * @param   string      $db_user        用户名
 * @param   string      $db_pass        密码
 * @param   string      $db_name        数据库名
 * @param   string      $prefix         数据表前缀
 * @return  boolean     成功返回true，失败返回false
 */
function create_config_file($db_host, $db_user, $db_pass, $db_name, $prefix, $charset)
{
    $content = '<?' . "php\n";
    $content .= "\$db['default']['hostname'] = \"$db_host\";    // 数据库主机地址 冒号后面是端口\n";
    $content .= "\$db['default']['username'] = \"$db_user\";    //数据库连接账户名\n";
    $content .= "\$db['default']['password'] = \"$db_pass\";    //数据库连接密码\n";
    $content .= "\$db['default']['database'] = \"$db_name\";    //数据库名\n";
    $content .= "\$db['default']['dbprefix'] = \"$prefix\";     //数据表前缀\n";
    $content .= "\$db['default']['char_set'] = \"$charset\";    //SET NAMES 编码\n";
    $content .= "\$db['default']['pconnect'] = FALSE;           //是否打开长连接\n";
    $content .= "\$db['default']['dbdriver'] = \"MySQL\";       //数据库类型 可以为 MySQl  MySQLi\n";
    $content .= "\$db['default']['resulttype'] = MYSQL_ASSOC;   //获取结果值的方式\n";
    $content .= '?>';

    $dataconfig = VAR_ROOT . 'Data/database.config.php';
    // 确定database.config.php文件存在并且可写
    if (is_writable($dataconfig)) {
        //打开文件
        if (!$fh = fopen($dataconfig, 'wb+')) {
            $msg = "不能打开文件 $dataconfig";
            $rs = '0';
        }
        // 写入内容
        elseif (fwrite($fh, $content) === FALSE) {
            $msg = "不能写入到文件 $dataconfig";
            $rs = '0';
        } else {
            $msg = "数据库配置文件已成功创建";
            $rs = '1';
            fclose($fh);
        }
    } else {
        $msg = "配置文件 $dataconfig 不可写,请赋其可写权限";
        $rs = '0';
    }
    $write_info['msg'] = $msg;
    $write_info['rs'] = $rs;
    return $write_info;
    exit();
}

/**
 * 创建指定名字的数据库
 *
 * @access  public
 * @param   string      $db_host        主机
 * @param   string      $db_port        端口号
 * @param   string      $db_user        用户名
 * @param   string      $db_pass        密码
 * @param   string      $db_name        数据库名
 * @param   string      $prefix         数据表前缀
 * @return  boolean     成功返回true，失败返回false
 */
function create_database($db_host, $db_user, $db_pass, $db_name, $prefix, $charset)
{
    global $errinfo;
    $conn = @mysql_connect($db_host, $db_user, $db_pass);

    if ($conn === false) {
        $errinfo = '连接 数据库失败，请检查您输入的 数据库帐号 是否正确。';
        return false;
    }

    $mysql_version = mysql_get_server_info($conn);
    keep_right_conn($conn, $mysql_version);
    if (mysql_select_db($db_name, $conn) === false) {
        $sql = $mysql_version >= '4.1' ? "CREATE DATABASE `$db_name` DEFAULT CHARACTER SET " . $GLOBALS['dbinfo']['char_set'] : "CREATE DATABASE $db_name";
        if (mysql_query($sql, $conn) === false) {
            $errinfo = '无法创建数据库';
            return false;
        }
    }
    @mysql_close($conn);

    return true;
}

/**
 * 保证进行正确的数据库连接（如字符集设置）
 *
 * @access  public
 * @param   string      $conn                      数据库连接
 * @param   string      $mysql_version        mysql版本号
 * @return  void
 */
function keep_right_conn($conn, $mysql_version='')
{
    if ($mysql_version === '') {
        $mysql_version = mysql_get_server_info($conn);
    }

    if ($mysql_version >= '4.1') {
        mysql_query('SET character_set_connection=' . $GLOBALS['dbinfo']['char_set'] . ', character_set_results=' . $GLOBALS['dbinfo']['char_set'] . ', character_set_client=binary', $conn);

        if ($mysql_version > '5.0.1') {
            mysql_query("SET sql_mode=''", $conn);
        }
    }
}

function doRevertData($bkdir, $filelist_string, $structfile = '')
{
    global $db;
    $bakfilesTmp = $filelist_string;
    $bakfiles_array = explode(',', $filelist_string);
    if (empty($structfile)) { // 表节构信息
        $structfile = "";
    }
    if (empty($startgo)) { //
        $startgo = 0;
    }
    if ($startgo == 0 && $structfile != '') { //第一次开始 有表节构信息
        $tbdata = ''; //初始还原数据
        $fp = fopen("$bkdir/$structfile", 'r');
        while (!feof($fp)) {
            $tbdata .= fgets($fp, 1024);
        }
        fclose($fp); //完成对节构表的读取
        $querys = explode(';', $tbdata);

        foreach ($querys as $q) {
            //替换表前缀
            $q = Rpdbprefix($q);
            $db->query(trim($q) . ';');
        }

        $revert_info['msg'] = "完成写入数据表信息，准备写入数据";
        $revert_info['startgo'] = 1;
        $revert_info['bakfiles'] = $bakfilesTmp;
        return $revert_info;
        exit();
    } else { //表节构还原完成 开始还原数据
        $nowfile = $bakfiles_array[0];
        $string = "zhuna_sysconfig_0_68886725cef6eec7.txt";
        preg_match("/([a-zA-Z])+_([a-zA-Z]+)_/", $nowfile, $nowfile_name);
        $nowfile_name = $GLOBALS['dbinfo']['dbprefix'] . $nowfile_name[2];
        $bakfilesTmp = preg_replace('/'.$nowfile . "[,]{0,1}/", "", $bakfilesTmp);
        $oknum = 0;

        if (filesize("$bkdir/$nowfile") > 0) {
            $fp = fopen("$bkdir/$nowfile", 'r');
            while (!feof($fp)) {
                $line = trim(fgets($fp, 512 * 1024));
                if ($line == "") {
                    continue;
                }
                //替换表前缀
                $line = Rpdbprefix($line);
                $rs = $db->execute($line);
                if ($rs) {
                    $oknum++;
                }
            }
            fclose($fp);
        }
        if ($bakfilesTmp == "") {
            $revert_info['where'] = 'over';
            $revert_info['msg'] = "<font color='red'>成功安装所有的数据表的数据！正在跳转安装下一步...</font><br>";
            $revert_info['msg'] .= "成功写入<font color='blue'>{$nowfile_name}</font>表 <font color='blue'>{$oknum}</font>条记录";
            $revert_info['startgo'] = 1;
            $revert_info['bakfiles'] = $bakfilesTmp;
            return $revert_info;
            exit();
        }
        $revert_info['where'] = '';
        $revert_info['msg'] = "成功写入<font color='blue'>{$nowfile_name}</font>表 <font color='blue'>{$oknum}</font>条记录, &nbsp;&nbsp;&nbsp;正在准备写入其它数据";
        $revert_info['startgo'] = 1;
        $revert_info['bakfiles'] = $bakfilesTmp;
        return $revert_info;
        exit();
    }
}

/**
 * 还原sql的时候把prefix数据库表前缀也更新了
 * @param <type> $sql
 */
function Rpdbprefix($sql)
{
    $prefix_search = array('INSERT INTO `zhuna_', 'CREATE TABLE `zhuna_', 'DROP TABLE IF EXISTS `zhuna_');
    $prefix_replace = array("INSERT INTO `{$GLOBALS['dbinfo']['dbprefix']}", "CREATE TABLE `{$GLOBALS['dbinfo']['dbprefix']}", "DROP TABLE IF EXISTS `{$GLOBALS['dbinfo']['dbprefix']}");
    $prefix_sql = str_replace($prefix_search, $prefix_replace, $sql);
    return $prefix_sql;
}

/**
 * 检测住哪联盟uid和mid的
 * @param <type> $agent_id
 * @param <type> $agent_md
 * @return <type>
 */
function checkAgent($agent_id, $agent_md)
{
    $host = $_SERVER['HTTP_HOST'];
    $ver = $GLOBALS['TmacConfig']['config']['version'];
    $apiUrl = "http://m.api.zhuna.cn/count/setup.php?v=php_v2&var=$ver&uid=$agent_id&mk=$agent_md&host=$host";
    $dom = new DomDocument;
    $dom_load = $dom->load($apiUrl);
    $rs = $dom->getElementsByTagName('result');
    $rs = $rs->item(0)->nodeValue;
    if ($rs == 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * 更新后台一些配置文件
 * @global  $db
 * @param <type> $agent_id
 * @param <type> $agent_md
 * @param <type> $agent_postmd
 * @param <type> $cfg_webname
 * @param <type> $cfg_indexurl
 * @return <type>
 */
function saveConfig($agent_id, $agent_md, $agent_postmd, $cfg_webname, $cfg_indexurl)
{
    global $db;
    $info = array(
        'value' => $agent_id
    );
    $where = "varname = 'cfg_uid'";
    $rs = $db->autoExecute('#@__sysconfig', $info, 'UPDATE', $where);

    $info = array(
        'value' => $agent_md
    );
    $where = "varname = 'cfg_mid'";
    $rs = $db->autoExecute('#@__sysconfig', $info, 'UPDATE', $where);

    $info = array(
        'value' => $agent_postmd
    );
    $where = "varname = 'cfg_key'";
    $rs = $db->autoExecute('#@__sysconfig', $info, 'UPDATE', $where);

    $info = array(
        'value' => $cfg_webname
    );
    $where = "varname = 'cfg_webname'";
    $rs = $db->autoExecute('#@__sysconfig', $info, 'UPDATE', $where);

    $info = array(
        'value' => $cfg_indexurl
    );
    $where = "varname = 'cfg_indexurl'";
    $rs = $db->autoExecute('#@__sysconfig', $info, 'UPDATE', $where);
    if ($rs) {
        return true;
    } else {
        return false;
    }
}

/**
 * 更新账号和密码信息
 * @global <type> $db
 * @param <type> $username
 * @param <type> $password
 * @param <type> $agent_md
 * @return <type>
 */
function saveAdmin($username, $password, $agent_md)
{
    global $db;
    $info = array(
        'username' => $username,
        'password' => md5($password.'^'.$agent_md)
    );
    $where = "id = 1";
    $rs = $db->autoExecute('#@__admin', $info, 'UPDATE', $where);
    if ($rs) {
        return true;
    } else {
        return false;
    }
}

/**
 * 写静态配置文件config.cache.php
 */
function ReWriteConfig()
{
    global $db;
    $configfile = ROOTDATA . 'config.cache.inc.php';
    if (!is_writeable($configfile)) {
        echo "配置文件'{$configfile}'不支持写入，无法修改系统配置参数！";
        exit();
    }
    $fp = fopen($configfile, 'w');
    flock($fp, 3);
    fwrite($fp, "<" . "?php\r\n");
    $getconfig = $db->getAll("select * from #@__sysconfig");
    foreach ($getconfig as $k => $v) {
        fwrite($fp, "\${$v['varname']} = '" . $v['value'] . "';\r\n");
    }
    fwrite($fp, "?" . ">");
    fclose($fp);
}

/**
 * 安装成功写install.lock
 */
function writeInstallLock()
{
    /* 写入安装锁定文件 */
    $fp = @fopen(ROOTDATA . 'install.lock', 'wb+');
    if (!$fp) {
        redirect('打开install.lock文件失败,请检查是否有文件读写权限');
        return false;
    }
    if (!@fwrite($fp, "TRADE SHOP INSTALLED")) {
        redirect('写入install.lock文件失败,请检查是否有文件读写权限');
        return false;
    }
    @fclose($fp);
    return true;
}

/**
 * 检查是否安装数据库在第三步 写网站配置的时候
 * @global $db $db
 */
function checkdatabase()
{
    global $db;
    $sql = "SELECT * FROM #@__sysconfig LIMIT 0,1";
    $rs = $db->getRow($sql);
    if (!$rs) {
        redirect('请先安装数据库文件!', 'index.php?step=2');
    }
}

function debugAjax($info)
{
    $file_info = var_export($info, true);
    $ok = file_put_contents(TMAC_ROOT . "/file_info.txt", $file_info);
    if ($ok)
        exit('true');
    exit('false');
}

?>